// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include "commoncppproblem654.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=654 lang=cpp
 *
 * [654] 最大二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(vector<int>& nums,int left,int right)
    {
        if(left>right)
        {
            return NULL;
        }

        //开始寻找最大节点
        int index = -1;
        int maxVal = -1;
        for(int i = left ;i <= right ; i++)
        {
            if(nums[i]>maxVal)
            {
                index = i;
                maxVal = nums[i];
            }
        }

        //构造节点
        TreeNode *root = new TreeNode(maxVal);
        root->left = build(nums,left,index-1);
        root->right = build(nums,index+1,right);
        return root;
    }

    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return build(nums,0,nums.size()-1);
    }
};
// @lc code=end

